package cn.itsource.controller;

import cn.itsource.utils.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/s")
public class SessionController {

    @GetMapping("/create")
    public R<Void> create(HttpServletRequest request, HttpSession session) {
        // 1.使用请求对象获取Session对象
        HttpSession sessionRequest = request.getSession();
        // 2.直接接收一个Session对象，两种方式获取到的是同一个Session对象，一个客户端就一份
        System.out.println(sessionRequest == session);
        // 3.响应
        return R.ok("Session获取成功");
    }

    @GetMapping("/add")
    public R<Void> add(HttpServletRequest request) {
        // 1.获取Session对象 - 从服务器获取如果没有就创建，如果有就是获取
        HttpSession session = request.getSession();
        // 2.设置键值对
        session.setAttribute("name","张三");
        session.setAttribute("age",306);
        // 3.响应
        return R.ok("Session添加数据成功");
    }

    @GetMapping("/find")
    public R<Void> find(HttpServletRequest request) {
        // 1.获取Session对象
        HttpSession session = request.getSession();
        // 2.获取数据
        Object name = session.getAttribute("name");
        System.out.println(name);
        // 3.响应
        return R.ok("Session获取数据成功");
    }

    @GetMapping("/del")
    public R<Void> del(HttpServletRequest request) {
        // 1.获取Session对象
        HttpSession session = request.getSession();
        // 2.删除数据
        session.removeAttribute("name");
        // 3.响应
        return R.ok("Session删除数据成功");
    }


    @GetMapping("/destory")
    public R<Void> destory(HttpServletRequest request) {
        // 1.获取Session对象
        HttpSession session = request.getSession();
        // 2.销毁对象
        session.invalidate();
        // 3.响应
        return R.ok("Session销毁成功");
    }

}
